/**
 * @author yxw
 * date : 2014年1月31日 下午8:15:28 
 */
package com.tzinfo.tzb;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.galhttprequest.GalHttpRequest;
import com.galhttprequest.GalHttpRequest.GalHttpLoadTextCallBack;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tzinfo.data.TztData;
import com.tzinfo.tzb.domain.ClassList.ClassData.ClassSubMenu;
import com.tzinfo.tzb.domain.ForumthreadList;
import com.tzinfo.tzb.domain.ForumthreadList.ForumthreadData;
import com.tzinfo.tzb.domain.ForumthreadList.ForumthreadData.Attachment;
import com.tzinfo.tzb.util.TzbCommonData;
import com.tzinfo.tzt.R;
import com.yxw.util.OutLog;
import com.yxw.util.YXWDateUtil;
import com.yxw.view.YXWXListView;
import com.yxw.view.YXWXListView.IXListViewListener;
import com.yxw.view.adapter.ImageAdapter;
import com.yxw.view.util.ResFinder;

public class TzbBangForumthreadListActivity extends TzbBaseActivity implements
		IXListViewListener {
	// 标志
	private boolean isCreate = true;
	// 参数
	private ClassSubMenu classSubMenu = null;

	// 适配器
	private ImageAdapter imageAdapter;

	// 数据
	private List<Map<String, Object>> data;

	// UI组件
	private YXWXListView listView;
	private ImageView image_theme_title;
	private TextView text_theme_title;
	private RelativeLayout layout_under_top;
	private Animation topInAnimation;
	private Animation topOutAnimation;

	// 其他
	private Handler mHandler;
	private int page = 1; // 页码
	private int pagesize = 10; // 每页条数

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tzb_ac_main_bang_forumthreadlist);
		initParameter();
		initAnimation();
		initUI();
		initData();
		listView.setSelection(TzbCommonData.POSITION);
	}

	private void initParameter() {
		// Intent thisIntent = this.getIntent();
		// classSubMenu = (ClassSubMenu) thisIntent
		// .getSerializableExtra("classSubMenu");
		classSubMenu = TzbCommonData.classSubMenu;
		mHandler = new Handler();
	}

	private void initAnimation() {
		topOutAnimation = AnimationUtils.loadAnimation(
				TzbBangForumthreadListActivity.this,
				ResFinder.getR(this, "R.anim.top_out"));
		topOutAnimation.setFillBefore(true);
		topOutAnimation.setFillAfter(true);
		topInAnimation = AnimationUtils.loadAnimation(
				TzbBangForumthreadListActivity.this,
				ResFinder.getR(this, "R.anim.top_in"));
		topInAnimation.setFillBefore(true);
		topInAnimation.setFillAfter(true);
		topInAnimation.setAnimationListener(new AnimationListener() {

			@Override
			public void onAnimationStart(Animation animation) {

			}

			@Override
			public void onAnimationRepeat(Animation animation) {

			}

			@Override
			public void onAnimationEnd(Animation animation) {
				layout_under_top.setVisibility(View.VISIBLE);
				listView.setPadding(0, layout_under_top.getHeight(), 0, 0);
			}
		});
	}

	private void initUI() {
		// 加载滚动进入条
		mProgressBar = (ProgressBar) this.findViewById(ResFinder.getR(this,
				"R.id.progressbar_loding"));
		image_theme_title = (ImageView) ResFinder.findViewById(this,
				"R.id.image_theme_title");
		text_theme_title = (TextView) ResFinder.findViewById(this,
				"R.id.text_theme_title");
		imageLoader.displayImage(classSubMenu.getPicFile() + "",
				image_theme_title, options);
		text_theme_title.setText(classSubMenu.getName());
		listView = (YXWXListView) ResFinder
				.findViewById(this, "R.id.xListView");
		layout_under_top = (RelativeLayout) ResFinder.findViewById(this,
				"R.id.layout_under_top");

		int w = View.MeasureSpec.makeMeasureSpec(0,
				View.MeasureSpec.UNSPECIFIED);
		int h = View.MeasureSpec.makeMeasureSpec(0,
				View.MeasureSpec.UNSPECIFIED);
		layout_under_top.measure(w, h);
		int width = layout_under_top.getMeasuredWidth();
		int height = layout_under_top.getMeasuredHeight();

		listView.setPadding(0, height, 0, 0);
		listView.setPullLoadEnable(true);
		listView.setPullRefreshEnable(true);
		listView.setXListViewListener(this);

		// 设置分类栏的消失动画
		listView.setOnTouchListener(new OnTouchListener() {
			double statrY = 0;
			double endY = 0;

			@Override
			public boolean onTouch(View view, MotionEvent motionevent) {
				if (motionevent.getAction() == MotionEvent.ACTION_DOWN) {
					statrY = motionevent.getY();
				} else if (motionevent.getAction() == MotionEvent.ACTION_MOVE) {
					endY = motionevent.getY();
					if ((statrY - endY >= layout_under_top.getHeight() + 30 || (listView
							.getFirstVisiblePosition() > 1 && statrY - endY >= 30))
							&& listView.getPaddingTop() != 0) {
						layout_under_top.startAnimation(topOutAnimation);
						layout_under_top.setVisibility(View.GONE);
						listView.setPadding(0, 0, 0, 0);
					} else if (endY - statrY >= 30
							&& listView.getPaddingTop() == 0) {
						layout_under_top.startAnimation(topInAnimation);
					}
				}
				return false;
			}
		});

		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapterview, View view,
					int i, long l) {
				Intent intent = new Intent(TzbBangForumthreadListActivity.this,
						TzbBangForumpostListActivity.class);
				// TzbDynamicData.setSCROLL(listView.getScrollX(),listView.getScrollY());
				TzbCommonData.POSITION = i;
				TzbCommonData.forumthreadData = TzbCommonData.forumthreadList
						.getData().get((int) l);
				startActivity(intent);
				// LoadActivityWithTabhost(intent,
				// TzbTabMyBangGroup.activityGroup);
			}
		});
	}

	private void initData() {
		if (isCreate || TzbCommonData.forumthreadList == null
				|| !TzbCommonData.forumthreadList.isSuccess()) {
			requestInfo();
			isCreate = false;
		} else {
			initListView();
		}
	}

	private void initListView() {
		// 初始化data
		if (data == null) {
			data = new ArrayList<Map<String, Object>>();
		} else {
			data.clear();
		}
		List<ForumthreadData> list = TzbCommonData.forumthreadList.getData();
		for (int i = 0; i < list.size(); i++) {
			Map<String, Object> map = new HashMap<String, Object>();
			List<Attachment> attlist = list.get(i).getAttachment();
			if (attlist != null && attlist.size() > 0
					&& attlist.get(0).getAttachment() != null
					&& !"".equals(attlist.get(0).getAttachment().trim())) {
				map.put("Avatar", attlist.get(0).getAttachment());
			} else {
				map.put("Avatar", list.get(i).getUserinfo().getAvatar());
			}

			String subject = list.get(i).getSubject();
			if (subject.length() >= 12) {
				subject = subject.substring(0, 12) + "…";
			}
			map.put("Subject", subject);
			map.put("Lastpost", "浏览:" + list.get(i).getViews() + "次");
			// 设置几秒前、几分前、几小时前等
			String sDateline = YXWDateUtil.getTimeInterval(list.get(i)
					.getDateline(), "MM/dd/yyyy HH:mm:ss");
			map.put("Dateline", sDateline);
			map.put("Replies", list.get(i).getReplies());
			data.add(map);
		}
		if (imageAdapter == null) {
			imageAdapter = new ImageAdapter(
					TzbBangForumthreadListActivity.this, data, ResFinder.getR(
							TzbBangForumthreadListActivity.this,
							"R.layout.tzb_item_forumthread"), new String[] {
							"Avatar", "Subject", "Lastpost", "Dateline",
							"Replies" }, new int[] {
							ResFinder.getR(TzbBangForumthreadListActivity.this,
									"R.id.list_item_image"),
							ResFinder.getR(TzbBangForumthreadListActivity.this,
									"R.id.list_item_title"),
							ResFinder.getR(TzbBangForumthreadListActivity.this,
									"R.id.list_item_context"),
							ResFinder.getR(TzbBangForumthreadListActivity.this,
									"R.id.list_item_time"),
							ResFinder.getR(TzbBangForumthreadListActivity.this,
									"R.id.list_item_reply") });
			listView.setAdapter(imageAdapter);
		} else {
			imageAdapter.notifyDataSetChanged();
		}
	}

	// 重载，默认请求新数据
	private void requestInfo() {
		page = 1;
		requestInfo(TzbCommonData.NOPULL_LOAD);
	}

	private void requestInfo(int type) {
		final int type2 = type;
		if (type == TzbCommonData.NOPULL_LOAD) {
			showProgressBar();
		}
		String url = ResFinder.getResString(this,
				"R.string.tzb_url_ForumthreadList")
				+ "?fid="
				+ classSubMenu.getForumId()
				+ "&Page="
				+ page
				+ "&Pagesize="
				+ pagesize;
		OutLog.LogE("url", url);
		GalHttpRequest galHttpRequest = new GalHttpRequest(this, url);
		galHttpRequest.startAsynRequestString(new GalHttpLoadTextCallBack() {

			@Override
			public void textLoaded(String arg0) {
				Gson gson = new Gson();
				java.lang.reflect.Type type = new TypeToken<ForumthreadList>() {
				}.getType();

				ForumthreadList forumthreadList = gson.fromJson(arg0, type);
				if (forumthreadList.isSuccess()) {
					if (type2 == TzbCommonData.PULL_LOAD_MORE) {
						int size = forumthreadList.getData().size();
						for (int i = 0; i < size; i++) {
							TzbCommonData.forumthreadList.getData().add(
									forumthreadList.getData().get(i));
						}
						if (size < 10) {
							listView.setPullLoadEnable(false);
							Toast.makeText(TzbBangForumthreadListActivity.this,
									"已经是最后一页！", Toast.LENGTH_LONG).show();
						}
					} else if (type2 == TzbCommonData.PULL_REFLASH
							|| type2 == TzbCommonData.NOPULL_LOAD) {
						TzbCommonData.forumthreadList = forumthreadList;
						if (forumthreadList.getData().size() < 10) {
							listView.setPullLoadEnable(false);
						} else {
							listView.setPullLoadEnable(true);
						}
					}
					initListView();
					onLoadFinish();
				} else {
					Toast.makeText(TzbBangForumthreadListActivity.this,
							"数据加载失败…", Toast.LENGTH_LONG).show();
				}
				removeProgressBar();
			}
		});
	}

	public void fatie(View v) {
		if (TztData.userInfo != null) {
			Intent intent = new Intent(this, TzbBangFatieActivity.class);
			startActivityForResult(intent, 1);
		} else {
			Toast.makeText(this, "亲，请先登录才能使用该功能", Toast.LENGTH_SHORT).show();
		}

	}

	// onclick方法
	@Override
	public void goTabHostBack(View v) {
		// Intent intent = new Intent(this, TzbMyBangAcivity.class);
		// LoadActivityWithTabhost(intent, TzbTabMyBangGroup.activityGroup);
		TzbCommonData.forumthreadList = null;
		TzbCommonData.POSITION = 0;
		this.finish();
	}

	private void onLoadFinish() {
		listView.stopRefresh();
		listView.stopLoadMore();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
		listView.setRefreshTime(df.format(new Date()));
	}

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				page = 1;
				requestInfo(TzbCommonData.PULL_REFLASH);
			}
		}, 2000);
	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				page++;
				requestInfo(TzbCommonData.PULL_LOAD_MORE);
			}
		}, 2000);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == 1) {
			if (resultCode == 1) {
				boolean isOk = data.getBooleanExtra(TzbCommonData.IS_OK, false);
				if (isOk) {
					requestInfo();
				}
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
}
